package com.it.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.reggie.common.BaseContext;
import com.it.reggie.common.Result;
import com.it.reggie.dto.OrdersDto;
import com.it.reggie.entity.OrderDetail;
import com.it.reggie.entity.Orders;
import com.it.reggie.service.IOrderDetailService;
import com.it.reggie.service.IOrderService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author:cyh
 * @data:2022/12/19 16:39
 */
@Api(tags = "订单管理")
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    IOrderService orderService;
    @Autowired
    IOrderDetailService orderDetailService;

    @PostMapping("/submit")
    public Result submit(@RequestBody Orders orders){
        orderService.sumit(orders);
        return Result.success("下单成功");
    }

    @GetMapping("/userPage")
    public Result<Page> query(Integer page,Integer pageSize){
        Page<Orders> orderPage = new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        Long userId = BaseContext.getCurrentId();
        //通过userId获取order
        LambdaQueryWrapper<Orders> orderswrapper = new LambdaQueryWrapper<>();
        orderswrapper.eq(Orders::getUserId, userId);
        orderService.page(orderPage, orderswrapper);

        ArrayList<OrdersDto> ordersDtos = new ArrayList<>();
        for (Orders orders : orderPage.getRecords()) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
            orderDetailWrapper.eq(OrderDetail::getOrderId, orders.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailWrapper);
            ordersDto.setOrderDetails(orderDetails);
            ordersDtos.add(ordersDto);
        }
        ordersDtoPage.setRecords(ordersDtos);
        return Result.success(ordersDtoPage);
    }

    @GetMapping("/page")
    public Result<Page<Orders>> page(Integer page, Integer pageSize, Long number, LocalDateTime beginTime,LocalDateTime endTime){
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(beginTime!=null, Orders::getOrderTime, beginTime);
        wrapper.like(endTime!=null, Orders::getOrderTime, endTime);
        wrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(ordersPage,wrapper);
        return Result.success(ordersPage);
    }

    /**
     * 导出订单
     */
    @GetMapping("/export")
    public void orderExport(HttpServletResponse response) throws IOException {
        //1、查询所有的订单数据 List<>
        List<Orders> orders = orderService.list();
        //对状态进行处理
        //订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        for (Orders order : orders) {
            Integer status = order.getStatus();
            if (status==1){
                order.setStatusStr("待付款");
            }else if (status==2){
                order.setStatusStr("待派送");
            }else if (status==3){
                order.setStatusStr("已派送");
            }else if (status==4){
                order.setStatusStr("已完成");
            }else if (status==5){
                order.setStatusStr("已取消");
            }
        }

        //2、将excel通过response响应流写入到浏览器
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //3、下载的文件名需要写死： 订单明细.xlsx 响应头：ContentDisposition
        String filename = URLEncoder.encode("订单明细","utf-8");
        //设置响应头
        response.setHeader("Content-Disposition","attachment;filename="+filename+".xlsx");
        //4、写入excel 【apache poi | 阿里的easy excel】
        //4.1 获取流对象
        ServletOutputStream outputStream = response.getOutputStream();
        //4.2 获取write对象
        ExcelWriterBuilder write = EasyExcel.write(outputStream, Orders.class);
        //4.3 获取数据表对象
        ExcelWriterSheetBuilder sheet = write.sheet();
        //4.4 生成表格文件
        sheet.doWrite(orders);

    }
}
